package com.hjm.project.ActActive.ActActive.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.yh.Utils;
import com.hjm.project.ActTerminalModel.ActTerminalModel.mapper.ActTerminalModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hjm.project.ActActive.ActActive.mapper.ActActiveMapper;
import com.hjm.project.ActActive.ActActive.domain.ActActive;
import com.hjm.project.ActActive.ActActive.service.IActActiveService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 活动配置Service业务层处理
 * 
 * @author LOVE
 * @date 2020-11-28
 */
@Service
public class ActActiveServiceImpl implements IActActiveService 
{
    @Autowired
    private ActActiveMapper actActiveMapper;


    @Autowired
    private ActTerminalModelMapper actTerminalModelMapper;

    /**
     * 查询活动配置
     * 
     * @param actId 活动配置ID
     * @return 活动配置
     */
    @Override
    public ActActive selectActActiveById(String actId)
    {
        return actActiveMapper.selectActActiveById(actId);
    }

    /**
     * 查询活动配置列表
     * 
     * @param actActive 活动配置
     * @return 活动配置
     */
    @Override
    public List<ActActive> selectActActiveList(ActActive actActive)
    {
        return actActiveMapper.selectActActiveList(actActive);
    }

    /**
     * 新增活动配置
     * 
     * @param actActive 活动配置
     * @return 结果
     */
    @Override
    public int insertActActive(ActActive actActive)
    {
        return actActiveMapper.insertActActive(actActive);
    }

    /**
     * 修改活动配置
     * 
     * @param actActive 活动配置
     * @return 结果
     */
    @Override
    public int updateActActive(ActActive actActive)
    {
        return actActiveMapper.updateActActive(actActive);
    }

    /**
     * 删除活动配置对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteActActiveByIds(String ids)
    {
        int num=actActiveMapper.getBindActive(ids);
        if (num>0){
            return -1;
        }
        ActActive oldAct=actActiveMapper.selectActActiveById(ids);
        if (oldAct.getStatus().equals(Long.parseLong("1"))){
            return -2;
        }
        ActActive actActive=new ActActive();
        actActive.setActId(ids);
        actActive.setStatus(Long.parseLong("1"));
        return actActiveMapper.updateActActive(actActive);
    }

    /**
     * 删除活动配置信息
     * 
     * @param actId 活动配置ID
     * @return 结果
     */
    @Override
    public int deleteActActiveById(String actId)
    {
        return actActiveMapper.deleteActActiveById(actId);
    }



    /**
     * 查询活动配置列表
     *
     * @param actActive 活动配置
     * @return 活动配置
     */
    @Override
    public List<ActActive> getActByAgent(ActActive actActive)
    {
        return actActiveMapper.getActByAgent(actActive);
    }

    /**
     * 查询激活返现配置的机具类型以及其返现金额
     * @param params Map
     * @return List
     */
    @Override
    public List<Map<String, String>> getActTerminalModelDetail(Map<String, String> params) {
        return actActiveMapper.getActTerminalModelDetail(params);
    }

    /**
     * 配置活动规则
     * @param actId 活动Id
     * @param data 规则数据
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addActReturnMoney(String actId, String data) {
        int result = 0;
        Map<String, String> actMap = Maps.newHashMap();
        if (!StringUtils.isEmpty(data)){
            JSONObject object = JSONObject.parseObject(data);
            //激活返现规则
            String activationReturnStr = object.getString("activationReturn");
            if (!StringUtils.isEmpty(activationReturnStr)){
                actMap.put("activation_rule","1");
                //存在激活返现功能
                JSONArray activationReturnArray = JSONArray.parseArray(activationReturnStr);
                //保存激活返现规则
                for (Object obj : activationReturnArray) {
                    Map<String, String> activationReturn = (Map<String, String>) obj;
                    activationReturn.put("act_id", actId);
                    actActiveMapper.mergeIntoActivationReturn(activationReturn);
                }
            }
            //交易达标(服务费)规则
            String standardReturn = object.getString("standardReturn");
            if (!StringUtils.isEmpty(standardReturn)){
                //交易达标(服务费)规则
                JSONArray standardReturnArray = JSONArray.parseArray(standardReturn);
                for(int i = 0; i< standardReturnArray.size(); i++){

                    JSONObject standardObject = JSONObject.parseObject(standardReturnArray.getString(i));
                    String type = standardObject.getString("type");
                    if ("0".equals(type)){
                        //交易达标
                        actMap.put("compliance_rule","1");
                    }else if("1".equals(type)){
                        //服务费
                        actMap.put("service_compliance_rule","1");
                    }
                    Map<String, String> standard = Maps.newHashMap();
                    standard.put("assessment_period", standardObject.getString("assessment_period"));
                    standard.put("return_cycle", standardObject.getString("return_cycle"));
                    standard.put("type", type);
                    standard.put("act_id", actId);
                    standard.put("id", standardObject.getString("id"));
                    //保存交易额返现表
                    actActiveMapper.mergeTransactionCompliance(standard);
                    String stageId= "transactionreturn" + standard.get("id");
                    //获取支付方式
                    String paymentTypeStr = standardObject.getString("paymentType");
                    if (!StringUtils.isEmpty(paymentTypeStr)){
                        JSONArray paymentTypeJsonArray = JSONArray.parseArray(paymentTypeStr);
                        for (Object obj : paymentTypeJsonArray) {
                            Map<String, String> paymentType = (Map<String, String>) obj;
                            paymentType.put("rule_id", stageId);
                            //根据支付类型指定商户类型，卡类型
                            Utils.setdistribution_typeMap(paymentType);
                            //保存支付方式表
                            actActiveMapper.mergePaymentType(paymentType);
                        }
                    }
                    //获取阶梯
                    String stageStr = standardObject.getString("stage");
                    if (!StringUtils.isEmpty(stageStr)){
                        JSONArray stageJsonArray = JSONArray.parseArray(stageStr);
                        for(int j =0; j < stageJsonArray.size();){
                            Map<String, String> stage = (Map<String, String>) stageJsonArray.get(j);
                            int stageNumber = ++j;
                            if (Integer.parseInt(stage.get("keep_money")) > Integer.parseInt(stage.get("matching_num"))) {
                                String msg = "达标额第" + (stageNumber -1) + "阶段留存金额不可大于返现金额";
                                if (stageNumber == 1) {
                                    msg = "激活额留存金额不可大于返现金额";
                                }
                                throw new BusinessException(msg);
                            }
                            stage.put("stage_id", stageId);
                            stage.put("type", "0");
                            stage.put("stage", String.valueOf(stageNumber));
                            actActiveMapper.mergeStage(stage);
                        }
                    }
                }
            }
          /*  ActActive actActive = new ActActive();
            actActive.setBuyMoney(ObjectUtils.isEmpty(object.get("buyMoney")) ? 0 : Integer.parseInt(object.get("buyMoney").toString()));
            actActive.setPosType(ObjectUtils.isEmpty(object.get("pos_type")) ? 4 : Integer.parseInt(object.get("pos_type").toString()));
            actActive.setProYlId(object.get("proYlId").toString());
            actActive.setAgentNum(object.get("agentNum").toString());
            actActive.setActId(actId);
            Integer money = Integer.parseInt(object.get("money").toString());
            Integer posType = Integer.parseInt(object.get("pos_type").toString());
            Integer maxVal = 120;
            if(posType == 5){
                 maxVal = 200;
            }else {
                maxVal = 120;
            }
            if(actActive.getBuyMoney() > maxVal){
                return maxVal;
            }
            if(actActive.getBuyMoney() + money > maxVal){
                return maxVal;
            }
            //保存活动购买人奖励金额
            actActiveMapper.updateActActive(actActive);*/

            String not_sa_money = object.getString("not_sa_money");
            if (StringUtils.isNotBlank(not_sa_money)) {
                String days = object.getString("days");
                String take_money = object.getString("take_money");
                Map params = new HashMap();
                params.put("act_id",actId);
                params.put("days",days);
                params.put("not_sa_money",not_sa_money);
                params.put("take_money",take_money);
                params.put("add_man", ShiroUtils.getLoginName());
                params.put("type", "0");
                actActiveMapper.insertWjh(params);
            }

            String days1 = object.getString("days1");
            if (StringUtils.isNotBlank(days1)) {
                String days = object.getString("days1");
                String take_money = object.getString("take_money1");
                Map params = new HashMap();
                params.put("act_id",actId);
                params.put("days",days);
                params.put("not_sa_money","");
                params.put("take_money",take_money);
                params.put("add_man", ShiroUtils.getLoginName());
                params.put("type", "1");
                actActiveMapper.insertWjh(params);
            }


            String sim_fee_return = object.getString("sim_fee_return");
            String sim_fee_keep = object.getString("sim_fee_keep");
            if (Integer.parseInt(sim_fee_keep) > Integer.parseInt(sim_fee_return)) {
                throw new BusinessException("流量卡费留存金额不可大于返现金额");
            }
            if (StringUtils.isNotBlank(sim_fee_return)) {
                Map params = new HashMap();
                params.put("act_id",actId);
                params.put("sim_fee_return",sim_fee_return);
                params.put("sim_fee_keep",sim_fee_keep);
                actActiveMapper.updateSimFee(params);
            }

            String service_fee_return = object.getString("service_fee_return");
            String service_fee_keep = object.getString("service_fee_keep");
            if (Integer.parseInt(service_fee_keep) > Integer.parseInt(service_fee_return)) {
                throw new BusinessException("服务费留存金额不可大于返现金额");
            }
            if (StringUtils.isNotBlank(service_fee_return)) {
                Map params = new HashMap();
                params.put("act_id",actId);
                params.put("service_fee_return",service_fee_return);
                params.put("service_fee_keep",service_fee_keep);
                actActiveMapper.updateServiceFee(params);
            }

            String award_leader = object.getString("award_leader");
            Map updateParams = new HashMap();
            updateParams.put("act_id",actId);
            if (StringUtils.isNotBlank(award_leader) && Integer.parseInt(award_leader) > 0) {
                updateParams.put("award_leader",award_leader);
            }

            String award_team = object.getString("award_team");
            if (StringUtils.isNotBlank(award_team) && Integer.parseInt(award_team) > 0) {
                updateParams.put("award_team",award_team);
            }

            String award_sales = object.getString("award_sales");
            if (StringUtils.isNotBlank(award_sales) && Integer.parseInt(award_sales) > 0) {
                updateParams.put("award_sales",award_sales);
            }
            Map params = new HashMap();
            params.put("act_id",actId);
            params.put("award_leader",award_leader);
            params.put("award_team",award_team);
            params.put("award_sales",award_sales);
            actActiveMapper.updateAwardMoney(params);

        }
        if (actMap.size() != 0){
            actMap.put("act_id", actId);
            result = actActiveMapper.updateActActiveRule(actMap);
        }
        return result;
    }

    public List<Map<String, String>> getLists(String obj) {
        return actActiveMapper.getLists(obj);
    }
    public Map selectWjh(String act_id,String type) {
        return actActiveMapper.selectWjh(act_id,type);
    }






    @Override
    public Map<String, Object> getActActive(Map<String, Object> map) throws Exception {
        List<Map<String, Object>> getActActive = actActiveMapper.getActActive( map);
        if(!Utils.IsNull(getActActive)&&getActActive.size()>0){
            return  getActActive.get(0);
        }
        return null;
    }


    @Override
    public int getNextval() throws Exception {
        return Integer.parseInt(String.valueOf(actActiveMapper.getNextval()));
    }


    @Override
    public boolean addActActive(Map<String, Object> map) throws Exception {
        return actActiveMapper.addActActive(map)>0;
    }

    public boolean batchInsertActTerminalModel(List<Map<String,Object>> list) throws Exception {
        return actTerminalModelMapper.batchInsertActTerminalModel(list)>0;
    }
    @Override
    public boolean updateActActives(Map<String, Object> map) throws Exception {
        return actActiveMapper.updateActActives(map)>0;
    }

    @Override
    public boolean setActActivationReturn(Map<String, Object> map) throws Exception {
        return actActiveMapper.setActActivationReturn(map)>0;
    }



}
